<template>
  <AuFormModal
    ref="formModalRef"
    v-model="showModal"
    :title="title"
    :formList="formList"
    :formData="selfFormData"
    :modalProps="{
      width: 460
    }"
    :formProps="{
      class: '!w-[386px]'
    }"
    @handleConfirm="handleConfirm"
  />
</template>

<script setup lang="ts">
import { AuFormModal } from "@/components/AuModal";
import { computed, nextTick, ref, watch } from "vue";
import { cloneDeep } from "lodash-unified";
import { tpmFormulaAdd, tpmFormulaUpd } from "@/api/teaPowder/formula";
import { ElMessage } from "element-plus";
import { getMaterialList } from "@/api/cabinet/formula";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

interface Props {
  modelValue: boolean;
  rowData: Object;
  versionId: string;
}

const props = defineProps<Props>();

const emits = defineEmits(["update:modelValue", "confirm"]);
const title = ref("");
const showModal = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emits("update:modelValue", value);
  }
});
const MAX_WEIGHT = 50;
const MIN_WEIGHT = 3;

const validate = (rule: any, value: any, callback: any) => {
  const intReg = new RegExp(/^(300|[1-9]|[1-9][0-9]|1[0-9]{2}|2[0-9]{2})$/);
  if (!intReg.test(value)) {
    return callback(new Error(t("formula_detail.times_warning")));
  }
  callback();
};

const validateSpeed = (rule: any, value: any, callback: any) => {
  // const intReg = new RegExp(/^([1-9]|[1-5][0-9]|60)$/);
  const intReg = new RegExp(/^([1-9]|10)$/);
  if (!intReg.test(value)) {
    return callback(new Error(t("formula_detail.level_warning")));
  }
  callback();
};

const formList = ref([
  {
    type: "input",
    key: "times",
    label: "formula_detail.times",
    placeholder: "formula_detail.times_placeholder",
    required: true,
    rules: [
      {
        validator: validate,
        trigger: "blur"
      }
    ]
  },
  {
    type: "input",
    key: "level",
    label: "formula_detail.level",
    placeholder: "formula_detail.level_placeholder",
    required: true,
    rules: [
      {
        validator: validateSpeed,
        trigger: "blur"
      }
    ]
  }
]);
const selfFormData = ref({});
const formModalRef = ref();

const handleConfirm = async (data: any) => {
  emits("update:modelValue", false);
  emits("confirm", data);
};

watch(
  () => [props.modelValue, props.rowData],
  ([val, row]) => {
    if (val) {
      const rowData = cloneDeep(row) as { [key: string]: any };
      title.value = rowData?.id
        ? t("formula_detail.edit_mode")
        : t("formula_detail.add_mode");
      if (rowData?.id) {
        nextTick(() => {
          formModalRef.value.setFormData(row);
        });
      } else {
        nextTick(() => {
          // getVersionList();
          formModalRef.value.reset();
        });
      }
    }
  }
);
</script>
